package com.yeskery.nut.core;

import com.yeskery.nut.util.ClassLoaderUtils;
import com.yeskery.nut.util.StringUtils;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * 类路径下的资源对象
 * @author sprout
 * @version 1.0
 * 2022-07-09 11:26
 */
public class ClassPathResource implements FileResource {

    /** 资源路径 */
    private final String path;

    /**
     * 构建类路径下的环境对象
     * @param path 资源路径
     */
    public ClassPathResource(String path) {
        this.path = path;
    }

    /**
     * 获取原始输入流对象
     * @return 原始输入流对象
     */
    protected InputStream getOriginalInputStream() {
        return ClassLoaderUtils.getClassLoader().getResourceAsStream(path);
    }

    @Override
    public InputStream getInputStream() {
        return getOriginalInputStream();
    }

    @Override
    public boolean exists() {
        return getURL() != null;
    }

    @Override
    public URI getURI() {
        try {
            return new URI(getURL().toString().replace(" ", "%20"));
        } catch (URISyntaxException e) {
            throw new NutException("ClassPathResource URI Obtain Fail.", e);
        }
    }

    @Override
    public URL getURL() {
        return ClassLoaderUtils.getClassLoader().getResource(path);
    }

    @Override
    public File getFile() {
        return new File(getURI().getSchemeSpecificPart());
    }

    @Override
    public long lastModified() {
        return getFile().lastModified();
    }

    @Override
    public boolean isReadable() {
        File file = getFile();
        return file.canRead() && !file.isDirectory();
    }

    @Override
    public boolean isOpen() {
        return false;
    }

    @Override
    public boolean isFile() {
        return getFile().isFile();
    }

    @Override
    public String getName() {
        return StringUtils.getFilename(path);
    }

    @Override
    public Long length() {
        return getFile().length();
    }
}
